import { getCurrentUser } from '@/services/auth';
import { App } from 'antd';

// 运行时配置

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
export async function getInitialState(): Promise<{ 
  name: string;
  currentUser?: any;
}> {
  const token = localStorage.getItem('token');
  
  if (token) {
    try {
      // 尝试获取当前用户信息
      const response = await getCurrentUser();
      if (response.success) {
        return { 
          name: 'LogWisdomHub',
          currentUser: response.data
        };
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 清除无效的token
      localStorage.removeItem('token');
      localStorage.removeItem('user');
    }
  }
  
  return { name: 'LogWisdomHub' };
}

// 添加 rootContainer 配置
export function rootContainer(container: any) {
  return (
    <App>
      {container}
    </App>
  );
}

export const layout = () => {
  return {
    logo: '/logo.svg',
    menu: {
      locale: false,
    },
    logout: async () => {
      try {
        // 调用后端登出接口
        await fetch('/api/accounts/logout/', {
          method: 'POST',
          headers: {
            'Authorization': `Token ${localStorage.getItem('token')}`
          }
        });
      } catch (error) {
        console.error('登出请求失败:', error);
      } finally {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = '/login';
      }
    },
  };
};

// 请求拦截器
export const request = {
  // 请求拦截器
  requestInterceptors: [
    (config: any) => {
      const token = localStorage.getItem('token');
      if (token) {
        // Django使用Token认证
        config.headers.Authorization = `Token ${token}`;
      }
      return config;
    },
  ],
  // 响应拦截器
  responseInterceptors: [
    (response: any) => {
      // 处理认证失败
      if (response.status === 401) {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = '/login';
      }
      return response;
    },
  ],
};
